package com.sinkdream.cms.controller;

import com.sinkdream.cms.model.News;
import com.sinkdream.cms.model.News_one;
import com.sinkdream.cms.service.NewsService_one;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@Controller
@RequestMapping("/ImgUpload")
public class ImgUploadController {
    @Value("${imgPath}")
    private String imgPath  ;//在配置文件配置的图片路径
    @Autowired
    private NewsService_one service;
    /**
     * 多图片上传，文章内容上传
     * @param file
     * @param title_op
     * @param texts
     * @return
     * @throws Exception
     */
    @RequestMapping("/upload")
    @ResponseBody
    @CrossOrigin
    public int fileUpload(@RequestParam(value="file",required = false) MultipartFile[] file, @RequestParam("title_op") String title_op, @RequestParam("texts") String texts) throws Exception {
        String fileName=null;
        int flag = 0;
        for (MultipartFile filess : file) {
            Long sizes=filess.getSize()/1024/1024;//单位 mb
            if(sizes>10){
                flag= 1;//文件大于10M
            }
        }
            StringBuilder sp = new StringBuilder();
        for (MultipartFile files : file) {
            if (files.isEmpty()) {
                System.out.println("文件为空");
                flag= 2;
            } else {
                fileName = files.getOriginalFilename();
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);//文件后缀名
                String filename0 = UUID.randomUUID()+"."+suffix;//文件名
                String filenames = imgPath+filename0;//路径+文件名
                sp.append(filename0+",");
                System.out.println("图片："+filenames);
               files.transferTo(new File(filenames));//保存到本地
                flag= 3;//成功
            }
        }
        News_one nes = new News_one();
        nes.setNewsType(7);//7代表群众，普通用户发表 （在身边位置显示）
        nes.setNewsTop(0);//0不置顶
        nes.setNewsAuthor(100000);//作者id
        nes.setNewsIsBanner(0);//0不是轮播图
        nes.setNewsTitle(title_op);//标题
        nes.setNewsContent(texts);//内容
        nes.setNews_title_img(sp.toString());//图片地址 address1,address2,address3,
        service.insertitlenews(nes);//插入数据

        System.out.println("图片地址："+sp);
        System.out.println("标题："+title_op);
        System.out.println("内容："+texts);
        return flag;
    }


}
